package com.jiangxiaofei.citycloud.activity.park;

import android.Manifest;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.district.DistrictSearchOption;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.poi.PoiSortType;
import com.baidu.mapapi.utils.DistanceUtil;
import com.blankj.utilcode.util.EmptyUtils;
import com.bumptech.glide.Glide;
import com.jiangxiaofei.citycloud.R;
import com.jiangxiaofei.citycloud.adapter.CarPartInfoPagerAdapter;
import com.jiangxiaofei.citycloud.adapter.CarResultAdapter;
import com.jiangxiaofei.citycloud.base.BaseActivity;
import com.jiangxiaofei.citycloud.bean.BaiduPlaceBean;
import com.jiangxiaofei.citycloud.bean.ParkBean;
import com.jiangxiaofei.citycloud.constants.Constants;
import com.jiangxiaofei.citycloud.constants.StringConstants;
import com.jiangxiaofei.citycloud.mvp.CarConstant;
import com.jiangxiaofei.citycloud.mvp.CarPersenter;
import com.jiangxiaofei.citycloud.param.BaiduPlaceParam;
import com.jiangxiaofei.citycloud.param.GetPartParam;
import com.jiangxiaofei.citycloud.service.LocationService;
import com.thinkcool.circletextimageview.CircleTextImageView;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import pub.devrel.easypermissions.EasyPermissions;

import static com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import static com.baidu.mapapi.map.MyLocationConfiguration.LocationMode.NORMAL;

/**
 * Created by JiangXFei on 2017/8/10.
 */

public class ParkMapAcitivity extends BaseActivity implements EasyPermissions.PermissionCallbacks,
        TextWatcher, CarConstant.GetBaiduPlaceView, AdapterView.OnItemClickListener, View.OnFocusChangeListener
        , BaiduMap.OnMapStatusChangeListener, CarConstant.GetParkView, ViewPager.OnPageChangeListener,
        BaiduMap.OnMarkerClickListener {
    public static final String TITLE = "title";
    @InjectView(R.id.map_mapv_show)
    MapView mapMapvShow;
    @InjectView(R.id.map_img_mtype)
    ImageView imgMtype;
    @InjectView(R.id.iv_leftone)
    ImageView ivLeftone;
    @InjectView(R.id.tv_centertitle)
    TextView tvCentertitle;
    @InjectView(R.id.iv_rightthree)
    ImageView ivRightthree;
    @InjectView(R.id.ll_return)
    LinearLayout llReturn;
    @InjectView(R.id.ll_centertitle)
    LinearLayout llCentertitle;
    @InjectView(R.id.et_car_map_search)
    EditText etCarMapSearch;
    @InjectView(R.id.tv_car_map_search)
    TextView tvCarMapSearch;
    @InjectView(R.id.linear_car_map_search)
    LinearLayout linearCarMapSearch;
    @InjectView(R.id.vp_car_part_info)
    ViewPager vpCarPartInfo;
    @InjectView(R.id.linear_car_map_buttom_cricle)
    LinearLayout linearCarMapButtomCricle;
    @InjectView(R.id.img_car_map_buttom_navigation)
    CircleTextImageView imgCarMapButtomNavigation;
    @InjectView(R.id.car_map_relative_buttom)
    RelativeLayout carMapRelativeButtom;
    private BaiduMap mBaiduMap;
    private String title;
    private LocationMode mCurrentMode;
    private LocationClient mLocClient;
    String[] perms = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_PHONE_STATE};
    public BDLocationListener myListener = new MyLocationListenner();
    private MapStatus.Builder builder;
    private LatLng ll;
    private boolean isSearchShow = false;
    private String city;
    private PopupWindow searResultPopup;
    private ListView recyCarSearch;
    private List<BaiduPlaceBean.ResultsBean> placeList = new ArrayList<>();
    private CarResultAdapter resultAdapter;
    private PoiSearch mPoiSearchNear;
    private LatLng latLng;
    private BaiduPlaceParam placeParam;
    private CarConstant.GetBaiduPlacePersenter getBaiduPlacePersenter;
    private CarConstant.GetParkPersenter getPartPersenter;
    private GetPartParam partParam;
    private List<PoiInfo> baiduPartList;
    private boolean isSeachOver = false;
    boolean isBaiduOver = false;
    boolean isSearch = false;
    private List<ParkBean.TwoKilometreParkListBean> pList = new ArrayList<>();
    private List<View> views;
    private CarPartInfoPagerAdapter pagerAdapter;
    private LatLng nowLatlng;
    private BitmapDescriptor parkSelectBitmap;


    @Override
    protected void initView(Bundle savedInstanceState) {
        mActivity = this;
        mContext = this;
        setContentView(R.layout.activity_car_map_layout);
        title = getIntent().getStringExtra(TITLE);
        ButterKnife.inject(this);
        placeParam = new BaiduPlaceParam();
        partParam = new GetPartParam();
        initSearchResultPopup();
        getBaiduPlacePersenter = new CarPersenter(mContext, (CarConstant.GetBaiduPlaceView) mActivity);
        getPartPersenter = new CarPersenter(mContext, (CarConstant.GetParkView) mActivity);
        if (EasyPermissions.hasPermissions(this, perms)) {
            initMap();
        } else {
            EasyPermissions.requestPermissions(this, "使用此功能需要读取您授予以下权限。",
                    200, perms);
        }
        carMapRelativeButtom.setVisibility(View.GONE);
        initViewpager();
    }

    //初始化VIEWPAGER
    private void initViewpager() {
        views = new ArrayList<>();
        pagerAdapter = new CarPartInfoPagerAdapter(views, mContext);
        vpCarPartInfo.setAdapter(pagerAdapter);
        vpCarPartInfo.addOnPageChangeListener(this);

    }


    //初始化地图层
    private void initMap() {
        mapMapvShow.showZoomControls(false);
        mBaiduMap = mapMapvShow.getMap();
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL); //设置为普通模式的地图
        mCurrentMode = NORMAL;
        mBaiduMap
                .setMyLocationConfigeration(new MyLocationConfiguration(
                        mCurrentMode, true, null));
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        mLocClient = new LocationClient(this);  //定位用到的一个类
        mLocClient.registerLocationListener(myListener); //注册监听
        mBaiduMap.setOnMapStatusChangeListener(this);
        ///LocationClientOption类用来设置定位SDK的定位方式，
        LocationClientOption option = new LocationService(mContext).getDefaultLocationClientOption(); //以下是给定位设置参数
        mLocClient.setLocOption(option);
        mLocClient.start();

        DistrictSearchOption districtSearchOption = new DistrictSearchOption();
        if (Constants.bdLocation != null) {
            city = Constants.bdLocation.getCity();
            latLng = new LatLng(Constants.bdLocation.getLatitude(), Constants.bdLocation.getLongitude());
            nowLatlng = latLng;
        } else {
            city = Constants.DEFAULTCITY;
        }
        districtSearchOption.cityName(city);//检索城市名称
        mPoiSearchNear = PoiSearch.newInstance();
        mPoiSearchNear.setOnGetPoiSearchResultListener(nearSearch);
        etCarMapSearch.addTextChangedListener(this);
        etCarMapSearch.setOnFocusChangeListener(this);
        getParkMark();
    }


    @Override
    protected void setListener() {
    }

    @Override
    protected void processLogic(Bundle savedInstanceState) {
    }


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @OnClick({R.id.map_img_mtype, R.id.iv_leftone, R.id.iv_rightthree, R.id.et_car_map_search})
    public void Onclick(View v) {
        switch (v.getId()) {
            case R.id.map_img_mtype:
                mCurrentMode = NORMAL;
                Glide.with(mContext).load(R.drawable.alp).into(imgMtype);
                mBaiduMap
                        .setMyLocationConfiguration(new MyLocationConfiguration(
                                mCurrentMode, true, null));
                builder.overlook(0);
                builder.target(ll).zoom(16);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                break;
            case R.id.iv_leftone:
//               返回按钮
                mActivity.finish();
                break;
            case R.id.iv_rightthree:
//               搜索框
                linearCarMapSearch.setVisibility(isSearchShow ? View.GONE : View.VISIBLE);
                isSearchShow = isSearchShow ? false : true;
                break;
            case R.id.et_car_map_search:
//                搜索编辑框
                break;
            default:
                break;
        }
    }

    boolean isFirstLoc = true; // 是否首次定位
    private MyLocationData locData;


    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (perms.size() == this.perms.length) {
            initMap();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {

    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        if (isSearch && EmptyUtils.isNotEmpty(charSequence.toString())) {
            placeParam.setRegion(city);
            placeParam.setQ(charSequence.toString());
            getBaiduPlacePersenter.getPlace();
        } else {
            searResultPopup.dismiss();
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {
        if (EmptyUtils.isEmpty(editable) || editable.length() == 0) {
            searResultPopup.dismiss();
        }
    }

    //获取地址成功
    @Override
    public void getPlaceSuccess(Object o) {
        List<BaiduPlaceBean.ResultsBean> results = (List<BaiduPlaceBean.ResultsBean>) o;
        if (results.size() > 0) {
            placeList.clear();
            placeList.addAll(results);
            resultAdapter.notifyDataSetChanged();
            searResultPopup.showAsDropDown(etCarMapSearch);
        } else {
            searResultPopup.dismiss();
        }
    }

    @Override
    public BaiduPlaceParam getBaiduPlace() {
        return placeParam;
    }


    //item点击监听
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//        etCarMapSearch.setFocusable(false);
        etCarMapSearch.setText("");
        etCarMapSearch.setHint(placeList.get(i).getName());
        latLng = new LatLng(placeList.get(i).getLocation().getLat(), placeList.get(i).getLocation().getLng());
        getParkMark();
        MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newLatLngZoom(latLng, 19);
        mBaiduMap.setMapStatus(mapStatusUpdate);
        searResultPopup.dismiss();
    }


    //重新获取地图点位并标记出来
    private void getParkMark() {
        mBaiduMap.clear();
        mPoiSearchNear.searchNearby(new PoiNearbySearchOption().keyword("停车场").location(latLng).radius(2000).sortType(PoiSortType.comprehensive));
        partParam.setCity(city);
        partParam.setLat(String.valueOf(latLng.latitude));
        partParam.setLng(String.valueOf(latLng.longitude));
        getPartPersenter.getPark();
    }

    @Override
    public void onFocusChange(View view, boolean b) {
        isSearch = b;
        if (!b) {
            searResultPopup.dismiss();
        }
    }

    /**
     * 地图状态改变监听start
     *
     * @param mapStatus
     */
    @Override
    public void onMapStatusChangeStart(MapStatus mapStatus) {

    }

    @Override
    public void onMapStatusChange(MapStatus mapStatus) {

    }

    @Override
    public void onMapStatusChangeFinish(MapStatus mapStatus) {
        LatLng move = mapStatus.bound.getCenter();
        isSeachOver = false;
        isBaiduOver = false;
        if (DistanceUtil.getDistance(latLng, move) > 200) {
            latLng = move;
            getParkMark();
        }
    }


    //获取停车场请求参数
    @Override
    public GetPartParam getPark() {
        return partParam;
    }

    //请求成功
    @Override
    public void onSuccessPart(Object o) {
        pList.clear();
        pList.addAll((List<ParkBean.TwoKilometreParkListBean>) o);
        if (pList.size() > 0) {
            isSeachOver = true;
//            isBaiduOver
//            if (isSeachOver) {
            addMapMark();
            setVpDate();
//            }
        }
    }

    private void setVpDate() {
        initViewpager();
        linearCarMapButtomCricle.removeAllViews();
        for (int i = 0; i < pList.size(); i++) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.vp_map_car_part_layout, null);
            TextView tvNumber, tvPrice, tvAdress, tvDistance, tvId, tvTitle;
            tvTitle = view.findViewById(R.id.tv_car_part_title);
            tvNumber = view.findViewById(R.id.tv_car_part_number);
            tvPrice = view.findViewById(R.id.tv_car_part_price);
            tvAdress = view.findViewById(R.id.tv_car_part_address);
            tvDistance = view.findViewById(R.id.tv_car_part_distance);
            tvId = view.findViewById(R.id.tv_car_part_id);
            final ParkBean.TwoKilometreParkListBean resultsBean = pList.get(i);
            tvTitle.setText(resultsBean.getParkName());
            tvNumber.setText(resultsBean.getVacancyNum() + "");
            tvId.setText((i + 1) + "、");
            tvAdress.setText(resultsBean.getParkAddress());
            LatLng searchPoint = new LatLng(resultsBean.getLat(), resultsBean.getLng());
            tvDistance.setText(String.valueOf((int) DistanceUtil.getDistance(searchPoint, nowLatlng)));
            tvPrice.setText(resultsBean.getPrice() + "");
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(mContext, ParkDetailActivity.class);
                    intent.putExtra(StringConstants.PARKSEQ, resultsBean.getParkSeq()+"");
                    mContext.startActivity(intent);
                }
            });
            views.add(view);
            setLinearCrecle(i);
        }
        carMapRelativeButtom.setVisibility(View.VISIBLE);
        pagerAdapter.notifyDataSetChanged();
    }

    private void setLinearCrecle(int i) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.view_cricle_layout, null);
        if (i == 0) {
            CircleTextImageView imgView = view.findViewById(R.id.cricle_view);
            imgView.setImageDrawable(getResources().getDrawable(R.color.maintab_text_selected_color));
        }
        linearCarMapButtomCricle.addView(view);

    }


    //添加网络搜索点位
    private void addMapMark() {
        for (int i = 0; i < pList.size(); i++) {
            Marker marker;
            ParkBean.TwoKilometreParkListBean twoKilometreParkListBean = pList.get(i);
            LatLng searchPoint = new LatLng(twoKilometreParkListBean.getLat(), twoKilometreParkListBean.getLng());
            //构建Marker图标
            BitmapDescriptor bitmap = BitmapDescriptorFactory
                    .fromResource(R.drawable.ic_part_car);
            //构建MarkerOption，用于在地图上添加Marker
            OverlayOptions option = new MarkerOptions()
                    .position(searchPoint)
                    .icon(bitmap);
            //在地图上添加Marker，并显示
            marker = (Marker) mBaiduMap.addOverlay(option);
            Bundle bundle = new Bundle();
            bundle.putParcelable("park", twoKilometreParkListBean);
            bundle.putInt("postion", i);
            marker.setExtraInfo(bundle);
            mBaiduMap.setOnMarkerClickListener(this);
        }
        setInfoWindow(0);
    }

    //添加百度地图搜索点位
    private void addBaiduMarker() {
        for (int i = 0; i < baiduPartList.size(); i++) {
            boolean isRepetition = true;
            PoiInfo poiInfo = baiduPartList.get(i);
            LatLng baiduPointl = new LatLng(poiInfo.location.latitude, poiInfo.location.longitude);
            for (int j = 0; j < pList.size(); j++) {
                LatLng searchPoint = new LatLng(pList.get(j).getLat(), pList.get(j).getLng());
                if (DistanceUtil.getDistance(searchPoint, baiduPointl) < 50) {
                    isRepetition = false;
                }
            }
            if (isRepetition) {
                BitmapDescriptor bitmap = BitmapDescriptorFactory
                        .fromResource(R.drawable.ic_cricle);
                //构建MarkerOption，用于在地图上添加Marker
                OverlayOptions option = new MarkerOptions()
                        .position(baiduPointl)
                        .icon(bitmap);
                //在地图上添加Marker，并显示
                mBaiduMap.addOverlay(option);

                mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
                    @Override
                    public boolean onMarkerClick(Marker marker) {
                        return true;
                    }
                });
            }
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    //viewpager滑动监听事件
    @Override
    public void onPageSelected(int position) {
        setCricleButtom(position);
        setInfoWindow(position);

    }

    private void setInfoWindow(int position) {
        parkSelectBitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.ic_park_select);
        LatLng lat = new LatLng(pList.get(position).getLat(), pList.get(position).getLng());
        InfoWindow infoWindow = new InfoWindow(parkSelectBitmap, lat, 10, new InfoWindow.OnInfoWindowClickListener() {
            @Override
            public void onInfoWindowClick() {

            }
        });
        mBaiduMap.showInfoWindow(infoWindow);
    }

    //设置列表底部小圆点
    private void setCricleButtom(int position) {
        if (linearCarMapButtomCricle.getChildCount() > 0) {
            for (int i = 0; i < linearCarMapButtomCricle.getChildCount(); i++) {
                View childAt = linearCarMapButtomCricle.getChildAt(i);
                CircleTextImageView imageView = childAt.findViewById(R.id.cricle_view);
                imageView.setImageDrawable(getResources().getDrawable(R.color.fontcolor14));
            }
            View childAt = linearCarMapButtomCricle.getChildAt(position);
            CircleTextImageView imageView = childAt.findViewById(R.id.cricle_view);
            imageView.setImageDrawable(getResources().getDrawable(R.color.maintab_text_selected_color));
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    //设置地图marker点击事件
    @Override
    public boolean onMarkerClick(Marker marker) {
        Bundle bundle = marker.getExtraInfo();
        int postion = bundle.getInt("postion", 0);
        vpCarPartInfo.setCurrentItem(postion);
        setInfoWindow(postion);
        return true;
    }


    /**
     * 地图状态改变监听end
     */

    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mBaiduMap == null) {
                return;
            }
            Constants.bdLocation = location;
            locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            if (isFirstLoc) {
                isFirstLoc = false;
                ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                builder = new MapStatus.Builder();
                builder.target(ll).zoom(16);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            }
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mapMapvShow.onDestroy();
        mPoiSearchNear.destroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mapMapvShow.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mapMapvShow.onPause();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    //初始化地图搜索下拉列表弹窗
    private void initSearchResultPopup() {
        searResultPopup = new PopupWindow();
        View view = LayoutInflater.from(mContext).inflate(R.layout.popup_map_search_result_layout, null, false);
        searResultPopup.setContentView(view);
        searResultPopup.setWidth(DrawerLayout.LayoutParams.WRAP_CONTENT);
        searResultPopup.setHeight(DrawerLayout.LayoutParams.WRAP_CONTENT);
        searResultPopup.setTouchable(true);
        searResultPopup.setBackgroundDrawable(new ColorDrawable(0x00000000));
        recyCarSearch = view.findViewById(R.id.recy_car_map_search_result);
        resultAdapter = new CarResultAdapter(mContext, placeList);
        recyCarSearch.setAdapter(resultAdapter);
        recyCarSearch.setOnItemClickListener(this);
    }

    //停车场搜索结果
    OnGetPoiSearchResultListener nearSearch = new OnGetPoiSearchResultListener() {
        @Override
        public void onGetPoiResult(PoiResult poiResult) {
            if (EmptyUtils.isNotEmpty(poiResult) && EmptyUtils.isNotEmpty(poiResult.getAllPoi()) && poiResult.getAllPoi().size() > 0) {
                isBaiduOver = true;
                baiduPartList = poiResult.getAllPoi();
                if (isBaiduOver && isSeachOver) {
                    addMapMark();
                }
            } else {
                isBaiduOver = false;
            }
        }

        @Override
        public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {

        }

        @Override
        public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

        }
    };
}
